import { ElMessage } from "element-plus";
import * as imageConversion from "image-conversion";

// 文件类型
export enum FILE_TYPE_CODE {
  IMAGE = "image", //图片
  VIDEO = "video", //视频
  AUDIO = "audio", //音频
  FILE = "file", //文件
}

// 通过远程图片地址获取文件流
export function getImageFileFromUrl(url: string): Promise<File> {
  // 截取图片名称
  let imageName = url.substring(url.lastIndexOf("/") + 1);
  return new Promise((resolve, reject) => {
    let blob = null;
    let xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.setRequestHeader("Accept", "image/png");
    xhr.responseType = "blob";
    xhr.onload = () => {
      blob = xhr.response;
      const contentDisposition = xhr.getResponseHeader("Content-Disposition");
      if (contentDisposition) {
        const match = contentDisposition.match(/filename="?([^"]+)"?/);
        if (match) imageName = match[1];
      }
      let imgFile = new File([blob], imageName);
      resolve(imgFile);
    };
    xhr.onerror = (e) => {
      reject(e);
    };
    xhr.send();
  });
}

// 压缩file
export async function compressImg(file: any) {
  return imageConversion.compressAccurately(file, 25);
}

// 截取视频的第一帧作为封面
export function getVideoBase64(url: string): Promise<Blob> {
  return new Promise(function (resolve, reject) {
    let dataURL = "";
    let video = document.createElement("video");
    video.setAttribute("crossOrigin", "anonymous"); //处理跨域
    video.setAttribute("src", url);
    video.setAttribute("width", "400");
    video.setAttribute("height", "240");
    video.setAttribute("preload", "auto");
    video.setAttribute("crossOrigin", "anonymous");
    video.addEventListener("loadeddata", function () {
      let canvas: any = document.createElement("canvas"),
        width = video.width, //canvas的尺寸和图片一样
        height = video.height;
      canvas.width = width;
      canvas.height = height;
      canvas.getContext("2d").drawImage(video, 0, 0, width, height); //绘制canvas
      dataURL = canvas.toBlob(async (blob: Blob) => {
        resolve(blob);
      });
    });
    video.addEventListener("error", function () {
      let error = "视频加载失败，请稍后再试";
      reject(error);
      ElMessage.error(error);
    });
  });
}

/**
 * 获取静态图片资源
 * @param name
 */
export const getStaticImage = (name: string): string => new URL(`../${name}`, import.meta.url).href;

/**
 * 获取文件格式标识，FILE_TYPE_CODE其中之一
 * @param fileName
 */
export function getFileExtension(fileName: string) {
  const extension = getFileFormat(fileName);
  const imageExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "webp"];
  const videoExtensions = ["mp4", "m4v", "mov", "avi", "mkv"];
  const audioExtensions = ["mp3", "wav", "ogg", "aac", "flac"];

  if (imageExtensions.includes(extension)) {
    return FILE_TYPE_CODE.IMAGE;
  } else if (videoExtensions.includes(extension)) {
    return FILE_TYPE_CODE.VIDEO;
  } else if (audioExtensions.includes(extension)) {
    return FILE_TYPE_CODE.AUDIO;
  } else {
    return FILE_TYPE_CODE.FILE;
  }
}

// 获取文件格式，例如 mp4
export function getFileFormat(fileName: string) {
  return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
}

// 显示文件大小
export function formatFileSize(size: number) {
  const units = ["B", "K", "M", "G", "T"];
  let idx = 0;

  while (size >= 1024 && idx < units.length - 1) {
    size /= 1024;
    idx++;
  }

  return `${size.toFixed(2)} ${units[idx]}`; // 保留两位小数
}
